using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
using WL.Think.Abp.Modules;

namespace WL.Think.Abp
{
    public class AppHostStartup
    {
        public static async Task<int> StartupAsync<TModule>(string[] args,Action<WebApplicationBuilder>? builderAction = null, Action<WebApplication>? appAction = null) where TModule : ThinkModule
        {
            Log.Logger = new LoggerConfiguration()
                .WriteTo.Async(c => c.File("Logs/logs.txt"))
                .WriteTo.Async(c => c.Console())
                .CreateBootstrapLogger();

            try
            {
                Log.Information("Starting Service");
                var builder = WebApplication.CreateBuilder(args);

                builderAction?.Invoke(builder);

                builder.Host.AddAppSettingsSecretsJson().UseAutofac()
                        .UseSerilog((context, services, loggerConfiguration) =>
                        {
                            loggerConfiguration
#if DEBUG
                                .MinimumLevel.Debug()
#else
                                .MinimumLevel.Information()
#endif
                                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                                .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                                .Enrich.FromLogContext()
                                .WriteTo.Async(c => c.File("Logs/logs.txt"))
                                .WriteTo.Async(c => c.Console());
                        });


                await builder.AddApplicationAsync<TModule>();

                var app = builder.Build();
                appAction?.Invoke(app);

                await app.InitializeApplicationAsync();
                await app.RunAsync();
                return 0;
            }
            catch (Exception ex)
            {
                if (ex is HostAbortedException)
                {
                    throw;
                }

                Log.Fatal(ex, "Host terminated unexpectedly!");
                return 1;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
    }
}
